<?php
namespace control;
class partsInventoryClass extends adIndexClass
{
    private const page = 'partsInventory';
    private const table = 'parts_take';
    private const tableMx = 'parts_take_detail';
    private const tableRecord = 'parts_inventory_record';
    private const title = '配件盘存';
    private const state = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'warehouse'  => [
                        'name'  => '盘点仓库',
                        'width' => 200,
                    ],
                    'surplus'         => [
                        'name'  => '盘盈数量',
                        'width' => 250,
                    ],
                    'loss'          => [
                        'name'  => '盘亏数量',
                        'width' => 250,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "盘点仓库"   => selectMultiple(['table' => 'warehouse', 'sqlField' => 'name', 'sqlId' => 'id', "where" => " coid = '" . self::$coid . "' and state = '启用' ".self::getWarehouseSql(), 'name' => 'warehouseId']),
                    "单据日期" => text(array("name" => "orderDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 列表-查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): string
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' ";
        $equal = [
            'orderNo' => $this->post('orderNo'),
            'warehouseId' => $this->post('warehouseId'),
        ];
        $like = [
            'state' => $this->post('state'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array(
                    "title" => self::title . "详情",
                    "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
                ),
                "edit" => $array['state'] == '草稿' ? [
                    "title" => "编辑",
                    "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')",
                ] : [],
            );
            $loss = self::lostZero(find([
                'table'  => self::tableMx,
                'single' => "orderId = '{$array['id']}' and orderNum > num",
                'field'  => "ifnull(sum(orderNum-num),0) as num",
            ])['num'],'numPrecision');
            $surplus = self::lostZero(find([
                'table'  => self::tableMx,
                'single' => "orderId = '{$array['id']}' and orderNum < num",
                'field'  => "ifnull(sum(num-orderNum),0) as num",
            ])['num'],'numPrecision');
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'surplus':
                        $row[] = $surplus;
                        break;
                    case 'loss':
                        $row[] = $loss;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "sum(if(num<orderNum,orderNum-num,0))numK,sum(if(num<orderNum,0,num-orderNum))numY ",
        ]);
        $total    = [
            'surplus'        => self::lostZero($total['numY'], 'numPrecision'),
            'loss'   => self::lostZero($total['numK'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 当前配件库存
     * @param $partsId
     * @param $warehouseId
     * @return float|int|string
     */
    public static function inventoryNum($partsId, $warehouseId = '')
    {
        $where = " and partsId = '$partsId' and coid = '" . self::$coid . "'";
        if ($warehouseId) {
            $where .= " and warehouseId  = '$warehouseId'";
        }
        return static::total([
            'sql' => 'SELECT IFNULL(sum(num), 0) as total FROM ' . self::tableRecord,
            'where' => $where,
        ]);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', '编码', '名称', '规格型号', '单位', '系统库存', '盘点库存'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
        $totalArr = ['inventoryNum'=>0,'num'=>0];
        foreach ((array)$result['array'] as $k=>$array) {
            $parts = query('parts', " id = '$array[partsId]'");
            $inventoryNum = self::inventoryNum($array['partsId']);
            $totalArr['inventoryNum'] += $inventoryNum;
            $totalArr['num'] += $array['num'];
            $tr[] =
                [
                    componentClass::tablePperation($k + 1) .
                    hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                    hidden(['name' => 'partsId[]', 'value' => $array['partsId']]),
                    $parts['code'],
                    $parts['name'],
                    $parts['model'],
                    $parts['unit'],
                    "<span class='inventoryNum'>".self::lostZero($inventoryNum, 'numPrecision')."</span>",
                    text(['name' => 'num[]', 'blur' => "textUpdate", 'value' => self::lostZero($array['num'], 'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                ];

        }
        $total = [
            5 => "<span id='total_inventory'>".self::lostZero($totalArr['inventoryNum'],'numPrecision')."</span>",
            6 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
        ];

        $table = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $mxButton = '';
        if ($this->power(self::page, "export")) {
            $mxButton .= "<span class='smallButton' onclick='exportInvntory()'>导出</span>\n";
        }
        $tableBut = <<<EOT
		    <span class="smallButton" onclick="getBookInventory()">获取账面库存</span>
            {$mxButton}
EOT;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '单据日期' => text(['name' => "recordDate", 'class' => 'text', 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date]),
                    must."仓库"=>selectMultiple(['table' => 'warehouse','value'=>$info['warehouseId'], "title" => '盘点仓库', 'sqlField' => 'name', 'sqlId' => 'id', "where" => " coid = '" . self::$coid . "' and state = '启用' ".self::getWarehouseSql(), 'name' => 'warehouseId']),
                    '类别' =>select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => para('partsType', '，')]),
                    '备注' => text(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $tableBut,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<EOT
			<script>
			//获取账面库存
			function getBookInventory(){
				$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addBookInventory', $('form[name=partsInventoryEditForm]').serialize(), function(res) {
			        if(res.warn !== 2){
			            msg(res.warn, 'error')
			        }else{
                        $("#materialTable tbody").empty().append(res.html);
                        calculateTotal()
			        }
			    }, 'json')
			}
			// 单个文本框更新
            function textUpdate(obj) {
                $(obj).css('background-color','#fdc1c1')
                calculateTotal()
            }
            //计算总数量
            function calculateTotal(){
                let table = $('.editList')
                let num = 0,
                inventoryNum = 0
                table.find("[name='num[]']").each(function(index){
                    if($(this).val()){
                      num+=Number($(this).val());
                    }
                    var inventoryNumText = table.find(".inventoryNum").eq(index).text()
                    if(inventoryNumText){
                        inventoryNum+=Number(inventoryNumText);
                    }
                })
                $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
                $("#total_inventory").text(inventoryNum.toFixed(publicSettings.numPrecision.num));
            }
			function exportInvntory(){
			    let warehouseId = $("[name='warehouseId']").val();
			     let arr = [];
                $("#materialTable input[name='partsId[]']").each(function () {
                     arr.push($(this).val());
                });
                if (arr.length > 0) {
                    let vals = arr.join(",");
                    window.open(root+"control/adIndex.html?cla={$this->get('cla')}&fun=exportInvntory&warehouseId="+warehouseId+"&listId="+vals);
                } else {
                    msg('请选择数据');
                }
			}
			</script>
EOT;
        //返回
        return $this->tab($data);
    }

    public function exportInvntory()
    {
        $listIds = $this->get('listId') ? explode(',', $this->get('listId')) : [];
        $warehouseId = $this->get('warehouseId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } elseif (static::is_null_array($listIds)) {
            $_SESSION['warn'] = '未找到导出的数据';
        } elseif(empty($warehouseId)){
            $_SESSION['warn'] = '请选择仓库';
        }else {
            $data = [];
            $title = ['编码', '名称', '规格型号', '单位', '系统库存', '盘点库存'];
            foreach ($listIds as $partsId) {
                $parts = query('parts', " id = '$partsId'");
                $inventoryNum = self::inventoryNum($partsId,$warehouseId);
                $data[] = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], self::lostZero($inventoryNum, 'numPrecision'), ''];
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 编辑
     *
     */
    public function addBookInventory(): string
    {
        $field = [
            'type' => $this->post('type'),
        ];
        $warehouseId = $this->post('warehouseId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif(empty($warehouseId)){
            $json['warn'] = '请选择盘点仓库';
        }else {
            $where = "coid = '" . self::$coid . "' and warehouseId = '$warehouseId'";
            if ($field['type']) {
                $where .= " and partsId IN (SELECT id FROM `parts` WHERE type = '$field[type]' ) ";
            }
            $result = find([
                'field' => '`partsId`, IFNULL(sum(num), 0) total ',
                'table' => self::tableRecord,
                'where' => $where . ' GROUP BY partsId',
            ]);
                $tr = [];
            $json['html'] = '';
                if (!static::is_null_array($result['array'])){
                    foreach ($result['array'] as $k=>$array) {
                        $parts = query('parts', "id = '$array[partsId]'");
                        $tr[] =
                            [
                                componentClass::tablePperation($k + 1) .
                                hidden(['name' => 'mxId[]', 'value' => suiji()]) .
                                hidden(['name' => 'partsId[]', 'value' => $array['partsId']]),
                                $parts['code'],
                                $parts['name'],
                                $parts['model'],
                                $parts['unit'],
                                "<span class='inventoryNum'>".self::lostZero($array['total'], 'numPrecision')."</span>",
                                text(['name' => 'num[]', 'blur' => "textUpdate", 'value' => self::lostZero($array['total'], 'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                            ];
                    }
                    $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
                }


                $json['warn'] = 2;
        }

        resp:
        return json_encode($json, 320);
    }

    public function editEdit(): string
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $partsIdArr = $this->post('partsId');
        $numArr = $this->post('num');
        $field = [
            'warehouseId'=>$this->post('warehouseId'),
            'recordDate' => $this->post('recordDate'),
            'type' => $this->post('type'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'recordDate' => '单据日期',
            'warehouseId' => '仓库',
        ];
        $rules = [
            'recordDate' => 'required|date',
             'warehouseId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " coid = '" . self::$coid . "' AND id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择盘点明细';
        } elseif (static::is_null_array($partsIdArr)) {
            $json['warn'] = '请选择盘点明细';
        } else {
            if (!empty($info['id']) && $info['state'] == '已确认') {
                $json['warn'] = '此配件盘存已确认，不能修改';
            } else {
                $this->startTrans();
                if (!$info['id']) {
                    $orderNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'PJPC' . date('Ymd', strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " AND coid = '" . self::$coid . "' ",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $orderNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }
                //添加或更新配件盘存明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                        $inventoryNum = self::inventoryNum($partsIdArr[$k]);
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'orderNum' => $inventoryNum,
                                    'num' => $numArr[$k] ?: 0,
                                ],
                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'partsId' => $partsIdArr[$k],
                                    'orderNum' => $inventoryNum,
                                    'num' => $numArr[$k] ?: 0,
                                ],
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    $this->commitTrans();
                    delete(
                        [
                            'table' => self::tableMx,
                            'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'",
                        ]
                    );
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = [
                "id" => $info['id'],
            ];
            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "取消",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[] = ['编码', '名称', '规格型号', '单位', '系统库存', '盘点库存', '差异'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            foreach ($result['array'] as $array) {
                $parts = query('parts', " id = '$array[partsId]'");
                $mxtr[] = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], self::lostZero($array['orderNum'], 'numPrecision'), self::lostZero($array['num'], 'numPrecision'), self::formattingFigure($array['num'] - $array['orderNum'], 'numPrecision')];
            }
            $total_tr = [
                4=>self::lostZero(array_sum(array_column((array)$result['array'],'orderNum')),'num'),
                5=>self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num'),
            ];
            $mxButton = '';
            if ($this->power(self::page, "export")) {
                $mxButton .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData&id=" . $info['id'] . "' class='smallButton'>导出</a>\n";
            }
            if ($info['state'] == '草稿' && $this->power(self::page, "import")) {
                $form = '<form name="excelForm" class="hide" method="post" enctype="multipart/form-data" action="' . root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=importData&orderId=' . $info['id'] . '">
                <input name="file" type="file" onchange="document.excelForm.submit()">
            </form>';
                $mxButton .= "<a href='" . root . "control/adIndex.php?cla=" . self::page . "&fun=downloadModel'><span class='smallButton'>导入模板</span></a>" .
                    "<span onclick=\"document.excelForm.file.click()\" class='smallButton'>Excel 导入</span>\n" . $form;
            }
//            if ($info['state'] == '已确认') {
//                $mxButton .= <<<EOT
//					<span class="smallButton" onclick="generateInventory('{$info['id']}', '盘盈单')">生成盘盈单</span>
//					<span class="smallButton" onclick="generateInventory('{$info['id']}', '盘亏单')">生成盘亏单</span>
//				EOT;
//            }
            $warehouse = query('warehouse',"id = '$info[warehouseId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        "单据日期" => $info['recordDate'],
                        '仓库'=>$warehouse['name'],
                        "分类" => $info['type'],
                        "单据编号" => $info['orderNo'],
                    ],
                    [
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '盘点明细',
                'button' => $mxButton,
                'html' => $this->listTable(array('tr' => $mxtr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data);
            // JS
            $html .= <<<EOT
			<script>
			//获取账面库存
			function getBookInventory(){
				$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addBookInventory', $('form[name=inventoryEditForm]').serialize(), function(res) {
			        if(res.warn !== 2){
			            msg(res.warn, 'error')
			        }else{
                        $("#materialTable tr").not('tr:eq(0)').remove()
                        $("#materialTable tr:eq(0)").after(res.html);
			        }
			    }, 'json')
			}
            //生成盈亏单
            function generateInventory(id, type){
            	$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=generateInventory', {'id': id, 'type': type}, function(res) {
			        if(res.warn === 2){
                        if (res.href) {
			                window.location.href = res.href;
			            } else {
			                window.location.reload();
			            }
			        }else{
				        msg(res.warn, 'error')
			        }
			    }, 'json')
            }
			</script>
EOT;
        }
        //返回
        return $html;
    }


    /**
     * Excel导入
     */
    public function importData()
    {
        $orderId = $this->get('orderId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $k = formSubArray($row);
                    //exportInvntory 为模板
                    $parts = query('parts', " coid = '" . self::$coid . "' AND code = '$k[0]' ");
                    if (!$parts['id']) {
                        $text .= "第【{$i}】行配件不存在，导入失败<br>";
                    } else {
                        $where = " coid = '" . self::$coid . "' and orderId = '{$orderId}' AND partsId = '{$parts['id']}'";
                        $inventory_take_detail = query(self::tableMx, $where, 'id');
                        if (!is_numeric($k[5])) {
                            $text .= "第【{$i}】行配件盘点库存只能填写数字<br>";
                        } elseif (empty($inventory_take_detail['id'])) {
                            $text .= "第【{$i}】行物料，未在当前配件盘存下<br>";
                        } else {
                            $k[5] = self::formattingFigure(floatval($k[5]), 'numPrecision');
                            $field = [
                                'num' => $k[5],
                            ];
                            $warn = static::update(["table" => self::tableMx, "field" => $field, 'where' => " id = '" . $inventory_take_detail['id'] . "' "]);
                            if (in_array($warn, ['新增成功', '更新成功'])) {
                                // 更新数量
                                $x++;
                                $text .= "第【{$i}】行导入成功<br>";
                            } else {
                                $text .= "第【{$i}】行导入失败：更新失败<br>";
                            }
                        }
                    }
                }
            }
            $warn = "成功导入{$x}条数据";
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = $warn;
        }
        $locationUrl = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $orderId;
        header("Location:" . $locationUrl);
        exit(0);
    }

    /**
     * 确认
     */
    public function confirmEdit(): string
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '已确认',
            //			'checkId'     => self::$stid,
            'confirmTime' => $this->time,
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } else {
            if (empty($info['id'])) {
                $json['warn'] = '未找到此配件盘存';
            } else {
                if ($info['state'] != '待确认') {
                    $json['warn'] = '此配件盘存不是待确认状态，不能确认';
                } else {
                    $json['warn'] = update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => "id = '$info[id]'",
                    ]);
                    //修改库存
                    $bool = $this->changeInventory($info['id']);
                    if ($bool!==true){
                        $json['warn'] = $bool;
                    }
                    if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                        auditingFollow([
                            "type" => "配件盘存",
                            "typeId" => $info['id'],
                            "text" => "【{$this->control['name']}】确认",
                        ]);
                        //添加日志
                        $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                        $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                        //返回
                        $_SESSION['warn'] = $json['warn'];
                        $json['warn'] = 2;
                        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                    }
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    public function changeInventory($id){
        $info = query(self::table,"id = '$id'");
        $all = find(array('table'=>self::tableMx,'where'=>"orderId = '$id' and orderNum != num order by list asc"));
        foreach ($all['array'] as $array){
            $warn = static::insert(array('table'=>self::tableRecord,
                'field'=>[
                    'id'=>suiji(),
                    'partsId'=>$array['partsId'],
                    'warehouseId'=>$info['warehouseId'],
                    'coid'=>self::$coid,
                    'num'=>$array['num']-$array['orderNum'],
                    'inventoryMxId'=>'',
                    'inventoryId'=>'',
                    'text'=>$array['num']>$array['orderNum']?'盘盈':'盘亏'
            ]));
            if ($warn !='新增成功'){
                return '修改库存失败';
            }
        }
        return true;
    }
    /**
     * 生产盈亏单
     *
     * @return string
     */
    public function generateInventory(): string
    {
        $id = $this->post('id');
        $type = $this->post('type');
        if (static::isNull($id)) {
            $json['warn'] = '参数错误';
        } else {
            $where = " orderId = '$id' ";
            if ($type == '盘盈单') {
                $mtype = '其他入库';
                $prefix = 'QTRK' . date('Ymd');
                $where .= " AND num > orderNum ";
                $subCategory = '盘盈';
                $classify = 1;
                $state = '待入库';
                $orderNo = codeTemplateClass::generateCode('inStockOther', [
                    'prefix' => $prefix,
                    'table' => 'inventory',
                    'where' => " AND coid = '" . self::$coid . "' ",
                ], []);
            } else {
                $mtype = '其他出库';
                $prefix = 'QTCK' . date('Ymd');
                $where .= " AND num < orderNum ";
                $subCategory = '盘亏';
                $classify = 0;
                $state = '待出库';
                $orderNo = codeTemplateClass::generateCode('outStockOther', [
                    'prefix' => $prefix,
                    'table' => 'inventory',
                    'where' => " AND coid = '" . self::$coid . "' ",
                ], []);
            }
            $total = static::total([
                'table' => 'inventory',
                'where' => [
                    'sourceTable' => self::table,
                    'sourceId' => $id,
                    'type' => $mtype,
                ],
            ]);
            $info = query(self::table, " id = '$id'");
            if (empty($info)) {
                $json['warn'] = self::title . '不存在';
            } elseif ($total > 0) {
                $json['warn'] = $mtype . '已存在此' . $type;
            } else {
                $result = find([
                    'table' => self::tableMx,
                    'where' => $where,
                ]);
                if (static::is_null_array($result['array'])) {
                    $json['warn'] = self::title . '无法生成' . $type;
                } else {
                    $inId = self::getId();
                    $this->startTrans();
                    static::insert([
                        'table' => 'inventory',
                        'field' => [
                            'id' => $inId,
                            'coid' => self::$coid,
                            'orderNo' => $orderNo,
                            'orderDate' => $this->date,
                            'type' => $mtype,
                            'subCategory' => $subCategory,
                            'classify' => $classify,
                            'sourceTable' => 'inventory_take',
                            'sourceId' => $info['id'],
                            'warehouseId' => $info['warehouseId'],
                            'state' => $state,
                            'stid' => self::$stid,
                        ],
                    ]);
                    if ($type == '盘盈单') {
                        $batch = inStockClass::getBatchNo('其他入库', '');
                        foreach ((array)$result['array'] as $value) {
                            $price = inventoryBalanceClass::unitPrice($value['materialId']);
                            $num = abs($value['num'] - $value['orderNum']);
                            static::insert([
                                'table' => 'inventory_detail',
                                'field' => [
                                    'id' => self::getId(),
                                    'coid' => self::$coid,
                                    'orderId' => $inId,
                                    'materialId' => $value['materialId'],
                                    'orderNum' => $value['orderNum'],
                                    'num' => $num,
                                    'price' => $price,
                                    'money' => round($num * $price, 2),
                                    'unit' => $value['unit'],
                                    'sourceTable' => 'inventory_take_detail',
                                    'sourceId' => $value['id'],
                                    'warehouseId' => $info['warehouseId'],
                                    'batch' => $batch,
                                ],
                            ]);
                        }
                    } else {
                        foreach ((array)$result['array'] as $value) {
                            $price = inventoryBalanceClass::unitPrice($value['materialId']);
                            $num = abs($value['num'] - $value['orderNum']);
                            //判断库存
                            $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $num, $value['unit']);
                            if (inventoryBalanceClass::inventoryNum($value['materialId'], $info['warehouseId']) - $mainUnitNum < 0) {
                                $json['warn'] = '盘亏数量不能大于库存数量';
                                goto resp;
                            }
                            //查询从早到晚的所有仓位和批次剩余的库存，依次出库
                            $fieldArr = self::resolveField([
                                'field' => '`id`, `coid`, `positionId`,`batch`, `materialId`, SUM(num) as num, `time`',
                                'group' => 'materialId,positionId,batch',
                            ]);
                            //查询结果
                            $where = " coid = '" . self::$coid . "' and materialId = '$value[materialId]' and warehouseId = '" . $info['warehouseId'] . "' ";
                            $where .= $fieldArr['group'];
                            $result = find(array('table' => 'inventory_record', 'field' => $fieldArr['field'], 'where' => $where . " having sum(num)>0 order by time "));
                            foreach ((array)$result['array'] as $array) {
                                if ($mainUnitNum > 0) {
                                    if ($mainUnitNum > $array['num']) {
                                        $now = $array['num'];
                                    } else {
                                        $now = $mainUnitNum;
                                    }
                                    $mainUnitNum -= $now;
                                    static::insert([
                                        'table' => 'inventory_detail',
                                        'field' => [
                                            'id' => self::getId(),
                                            'coid' => self::$coid,
                                            'orderId' => $inId,
                                            'materialId' => $value['materialId'],
                                            'orderNum' => $value['orderNum'],
                                            'num' => $now,
                                            'price' => $price,
                                            'money' => round($now * $price, 2),
                                            'unit' => $value['unit'],
                                            'sourceTable' => 'inventory_take_detail',
                                            'sourceId' => $value['id'],
                                            'warehouseId' => $info['warehouseId'],
                                            'positionId' => $array['positionId'],
                                            'batch' => $array['batch'],
                                        ],
                                    ]);
                                }
                            }
                        }
                    }
                    $this->commitTrans();//提交事务
                    $json['warn'] = 2;
                    $_SESSION['warn'] = $type . '生成成功';
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 取消
     */
    public function cancelEdit(): string
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId'     => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有取消权限';
        } else {
            if (empty($info['id'])) {
                $json['warn'] = '未找到此配件盘存';
            } else {
                $json['warn'] = update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => "id = '$info[id]'",
                ]);
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    auditingFollow(array(
                        "type" => "配件盘存",
                        "typeId" => $info['id'],
                        "text" => "【{$this->control['name']}】取消",
                    ));
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get(
                            'cla'
                        ) . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit(): string
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '待确认',
            'commitTime' => $this->time,
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } else {
            if (empty($info['id'])) {
                $json['warn'] = '未找到此配件盘存';
            } else {
                if ($info['state'] != '草稿') {
                    $json['warn'] = '此配件盘存不是草稿状态，不能提交';
                } else {
                    $json['warn'] = update(array(
                        "table" => self::table,
                        "field" => $field,
                        "where" => "id = '$info[id]'",
                    ));
                    if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                        auditingFollow([
                            "type" => "配件盘存",
                            "typeId" => $info['id'],
                            "text" => "【{$this->control['name']}】提交",
                        ]);
                        //添加日志
                        $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                        $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                        //返回
                        $_SESSION['warn'] = $json['warn'];
                        $json['warn'] = 2;
                        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                    }
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): string
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此配件盘存，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此配件盘存？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';

                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认取消此配件盘存？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';

                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';

                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): string|false
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } else {
            if (empty($array)) {
                $json['warn'] = "你一个数据都没有选择呢";
            } else {
                $text = "";
                $x = 0;
                $array = is_array($array) ? $array : [$array];
                foreach ($array as $id) {
                    $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                    if ($info['state'] == '已确认') {
                        $warn = "删除失败：已确认，暂不能删除";
                    } else {
                        //最后删除基本参数
                        delete(array("table" => self::table, "where" => " id = '$id' "));
                        delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                        delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                        //返回
                        $warn = "删除成功";
                        $x++;
                    }
                    $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
                }
                //添加日志
                $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
                $this->logText(array("type" => self::page, "text" => $text));
                $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $info = query(self::table, " id = '{$this->get('id')}' ");
            if (empty($info['id'])) {
                $_SESSION['warn'] = '记录不存在';
            } else {
                $data = [];
                $title = ['编码', '名称', '规格型号', '单位', '系统库存', '盘点库存', '差异'];
                $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
                foreach ($result['array'] as $array) {
                    $parts = query('parts', " id = '$array[partsId]'");
                    $data[] = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], self::lostZero($array['orderNum'], 'numPrecision'), self::lostZero($array['num'], 'numPrecision'), self::formattingFigure($array['num'] - $array['orderNum'], 'numPrecision')];
                }
                $text = $this->control['name'] . "导出了" . self::title;
                $this->logText(["type" => self::page, "text" => $text]);
                $this->excelOut($title, $data, self::title . ".xlsx");
            }
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
